package com.ptone.messageCenter.common.utils;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

@Component
public class HttpUtil {
    private String defaultContentEncoding;

    public HttpUtil() {
        this.defaultContentEncoding = Charset.defaultCharset().name();
    }

    public URLConnection sendGetRequest(String url, Map<String, Object> params, Map<String, Object> headers)
            throws Exception {
        StringBuilder buf = new StringBuilder(url);
        Set<Entry<String, Object>> entrys = null;
        if (params != null && !params.isEmpty()) {
            buf.append("?");
            entrys = params.entrySet();
            for (Entry<String, Object> entry : entrys) {
                buf.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"))
                        .append("&");
            }
            buf.deleteCharAt(buf.length() - 1);
        }
        URL url1 = new URL(buf.toString());
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        conn.setRequestMethod("GET");
        // ��������ͷ
        if (headers != null && !headers.isEmpty()) {
            entrys = headers.entrySet();
            for (Entry<String, Object> entry : entrys) {
                conn.setRequestProperty(entry.getKey(), entry.getValue().toString());
            }
        }
        conn.getResponseCode();
        return conn;
    }

    public URLConnection sendPostRequest(String url, Map<String, Object> params, Map<String, Object> headers)
            throws Exception {
        StringBuilder buf = new StringBuilder();
        Set<Entry<String, Object>> entrys = null;
        if (params != null && !params.isEmpty()) {
            entrys = params.entrySet();
            for (Entry<String, Object> entry : entrys) {
                buf.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"))
                        .append("&");
            }
            buf.deleteCharAt(buf.length() - 1);
        }
        URL url1 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        OutputStream out = conn.getOutputStream();
        out.write(buf.toString().getBytes("UTF-8"));
        if (headers != null && !headers.isEmpty()) {
            entrys = headers.entrySet();
            for (Entry<String, Object> entry : entrys) {
                conn.setRequestProperty(entry.getKey(), entry.getValue().toString());
            }
        }
        conn.getResponseCode(); // Ϊ�˷��ͳɹ�
        return conn;
    }

    public byte[] read2Byte(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }

    public String read2String(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return new String(outSteam.toByteArray(), "UTF-8");
    }

    public String read2String2(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return new String(outSteam.toByteArray(), "UTF-8");
    }

    public String postXml(String path, String xml, String encoding) throws Exception {
        byte[] data = xml.getBytes(encoding);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5 * 1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        if (conn.getResponseCode() == 200) {
            return read2String(conn.getInputStream());
        }
        return null;
    }

    public String getUrlWithParams(Map<String, String> paramsMap, String url) {
        StringBuffer sb = null;
        for (String key : paramsMap.keySet()) {
            if (sb == null) {
                sb = new StringBuffer();
                sb.append(url);
                sb.append("?");
            } else {
                sb.append("&");
            }

            sb.append(key);
            sb.append("=");
            sb.append(paramsMap.get(key));

        }

        return sb.toString();
    }

    public String getRemoteIp(HttpServletRequest req) {
        String ip = req.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }

        // squid的squid.conf 的配制文件中forwarded_for项改为off时
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getRemoteAddr();
        }

        // 多级反向代理
        if (ip != null && ip.indexOf(",") > 0 && ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    public void setDefaultContentEncoding(String defaultContentEncoding) {
        this.defaultContentEncoding = defaultContentEncoding;
    }

    public String getDefaultContentEncoding() {
        return this.defaultContentEncoding;
    }
}
